import { ItemStack, Player } from "@minecraft/server";
import { TimerTickEvent } from "@sapi-game/gameComponent/common/timer/tickEvent";
import { Timer } from "@sapi-game/gameComponent/common/timer/timer";
import { Game, GameComponent } from "@sapi-game/main";
import { eleCatchState } from "../state";

export class ElevatorSheepComponent extends GameComponent<eleCatchState> {
    private readonly sheepTime = 15;

    override onAttach(): void {
        const item = new ItemStack("minecraft:sheep_spawn_egg");
        item.nameTag = "放羊";
        this.context.cat.forEach((p) => p.giveItem(item));
        this.subscribe(
            Game.events.itemUse,
            (t) => {
                if (this.state.isSheep) {
                    return t.source.sendMessage("不能重复放羊");
                }
                const timer = this.state.getComponent(Timer);
                if (timer.time < this.sheepTime) {
                    return t.source.sendMessage("时间不足，无法放羊");
                }
                this.handleSheep(t.source);
            },
            {
                itemId: "minecraft:sheep_spawn_egg",
            }
        );
    }

    //成功放羊
    handleSheep(player: Player) {
        const timer = this.state.getComponent(Timer);

        this.context.group.sendMessage(
            `§e${player.name}放羊了，请在${this.sheepTime}秒内盗铃`
        );
        this.context.group.runCommand("clear @s sheep_spawn_egg");

        this.state.isSheep = true;
        timer.set(this.sheepTime);
        this.subscribe(timer.events.tick, this.sheepTitle.bind(this));
    }

    sheepTitle(t: TimerTickEvent) {
        this.context.group.title("放羊", `请在${t.remainingTime}秒内盗铃`);
    }
}
